#include "EventBus.h"

bool NahidaProject::EventBus::EventBusTopic::operator==(const EventBusTopic& other) const {
	return _index == other._index;
}

NahidaProject::EventBus::EventBusHandler<NahidaProject::EventBus::EventBusEvent>* NahidaProject::EventBus::EventBus::EventBusHandlerReference::GetHandler() const {
	return static_cast<EventBusHandler<EventBusEvent>*>(_handler);
}

const NahidaProject::EventBus::EventBusTopic* NahidaProject::EventBus::EventBus::EventBusHandlerReference::GetTopic() const {
	return _topic;
}

int NahidaProject::EventBus::EventBus::Publish(const EventBusEvent& e) {
	const std::type_index& index = typeid(e);
	EventBusHandlerReferenceMap::iterator i = _handlers.find(index);
	if (i == _handlers.end())
		return 0;

	int notifiedHandlers = 0;
	EventBusHandlerReferences& handlers = i->second;
	for (auto& r : handlers) {
		if (r.GetTopic() != nullptr) {
			const EventBusTopic* topic = e.GetTopic();
			if (topic == nullptr)
				continue;
			if (!(*r.GetTopic() == *topic))
				continue;
		}
		EventBusHandler<EventBusEvent>* handler = r.GetHandler();
		handler->Dispatch(e);
		++notifiedHandlers;
	}
	return notifiedHandlers;
}